package com.pxxy.mall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.pxxy.common.constant.SpuPublishStatus;
import com.pxxy.common.to.SkuHasStockVo;
import com.pxxy.common.to.SkuReductionTO;
import com.pxxy.common.to.SpuBoundTO;
import com.pxxy.common.to.es.SkuEsModel;
import com.pxxy.common.utils.R;
import com.pxxy.mall.product.dao.BrandDao;
import com.pxxy.mall.product.entity.*;
import com.pxxy.mall.product.feign.CouponFeignApi;
import com.pxxy.mall.product.feign.SearchFeignApi;
import com.pxxy.mall.product.feign.WareFeignApi;
import com.pxxy.mall.product.service.*;
import com.pxxy.mall.product.vo.SpuSaveVo;
import lombok.AllArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pxxy.common.utils.PageUtils;
import com.pxxy.common.utils.Query;

import com.pxxy.mall.product.dao.SpuInfoDao;
import org.springframework.transaction.annotation.Transactional;

@Service("spuInfoService")
@AllArgsConstructor
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    private SpuInfoDescService spuInfoDescService;
    private SpuImagesService spuImagesService;
    private ProductAttrValueService productAttrValueService;
    private AttrService attrService;

    private SkuSaleAttrValueServiceImpl skuSaleAttrValueService;

    private SkuInfoService skuInfoService;

    private SkuImagesService skuImagesService;

    private CouponFeignApi couponFeignApi;

    private BrandService brandService;

    private SearchFeignApi searchFeignApi;

    private WareFeignApi wareFeignApi;


    private CategoryService categoryService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        LambdaQueryWrapper<SpuInfoEntity> wrapper = new QueryWrapper<SpuInfoEntity>().lambda();

        String catelogId = (String) params.get("catelogId");
        if (StringUtils.isNotEmpty(catelogId)) {
            wrapper.eq(SpuInfoEntity::getCatalogId, catelogId);
        }
        String brandId = (String) params.get("brandId");
        if (StringUtils.isNotEmpty(brandId)) {
            wrapper.eq(SpuInfoEntity::getBrandId, brandId);
        }
        String status = (String) params.get("status");
        if (StringUtils.isNotEmpty(status)) {
            wrapper.eq(SpuInfoEntity::getPublishStatus, status);
        }
        String key = (String) params.get("key");
        if (StringUtils.isNotEmpty(key)) {
            wrapper.and(t -> {
                t.eq(SpuInfoEntity::getId, key).or().like(SpuInfoEntity::getSpuName, key);
            });
        }
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params), wrapper

        );

        return new PageUtils(page);
    }

    /**
     * 新增商品
     *
     * @param vo
     */
    @Transactional
    @Override
    public void saveSpuInfo(SpuSaveVo vo) {
        //1.保存spuinfo的基本信息
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());
        BeanUtils.copyProperties(vo, spuInfoEntity);
        this.save(spuInfoEntity);

        //保存decript图片
        List<String> decript = vo.getDecript();
        SpuInfoDescEntity descEntity = new SpuInfoDescEntity();
        descEntity.setSpuId(spuInfoEntity.getId());
        descEntity.setDecript(String.join(",", decript));
        spuInfoDescService.save(descEntity);

        //保存spu商品图片
        List<String> voImages = vo.getImages();
        if (voImages != null && voImages.size() != 0) {
            List<SpuImagesEntity> spuImagesEntities = voImages.stream().map(t -> {
                SpuImagesEntity spuImagesEntity = new SpuImagesEntity();
                spuImagesEntity.setSpuId(spuInfoEntity.getId());
                spuImagesEntity.setImgUrl(t);
                return spuImagesEntity;
            }).collect(Collectors.toList());
            spuImagesService.saveBatch(spuImagesEntities);
        }

        //保存spu的规格参数
        List<ProductAttrValueEntity> productAttrValueEntities = vo.getBaseAttrs().stream().map(t -> {
            ProductAttrValueEntity productAttrValueEntity = new ProductAttrValueEntity();
            //设置attrId，属性值，是否快速展示,spuId
            BeanUtils.copyProperties(t, productAttrValueEntity);
            productAttrValueEntity.setQuickShow(t.getShowDesc());
            productAttrValueEntity.setSpuId(spuInfoEntity.getId());
            productAttrValueEntity.setAttrValue(t.getAttrValues());
            //设置属性名
            productAttrValueEntity.setAttrName(attrService.getById(t.getAttrId()).getAttrName());
            return productAttrValueEntity;
        }).collect(Collectors.toList());
        productAttrValueService.saveBatch(productAttrValueEntities);

        //保存积分
        SpuBoundTO spuBoundTO = new SpuBoundTO();
        BeanUtils.copyProperties(vo.getBounds(), spuBoundTO);
        spuBoundTO.setSpuId(spuInfoEntity.getId());
        R r = couponFeignApi.saveSpuBound(spuBoundTO);
        if (r.getCode() != 0) {
            log.error("远程保存spu积分信息失败");
        }


        if (vo.getSkus() != null && vo.getSkus().size() > 0) {
            //保存当前spu对应的sku基本信息
            vo.getSkus().forEach(t -> {
                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                //设置spuId，sku名称，价格，标题，副标题
                BeanUtils.copyProperties(t, skuInfoEntity);
                skuInfoEntity.setSpuId(spuInfoEntity.getId());
                skuInfoEntity.setPrice(new BigDecimal(t.getPrice()));

                //设置所属分类,品牌的id,销量
                skuInfoEntity.setCatalogId(vo.getCatalogId());
                skuInfoEntity.setBrandId(vo.getBrandId());
                skuInfoEntity.setSaleCount(0L);
                //设置默认图片
                t.getImages().forEach(img -> {
                    if (img.getDefaultImg() == 1) {
                        skuInfoEntity.setSkuDefaultImg(img.getImgUrl());
                    }
                });
                //设置sku_desc描述
                List<String> descar = t.getDescar();
                skuInfoEntity.setSkuDesc(String.join(",", descar));
                skuInfoService.save(skuInfoEntity);

                //设置sku销售属性&值 pms_sku_sale_attr_value
                List<SkuSaleAttrValueEntity> skuSaleAttrValueEntities = t.getAttr().stream().map(attr -> {
                    SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();
                    BeanUtils.copyProperties(attr, skuSaleAttrValueEntity);
                    skuSaleAttrValueEntity.setSkuId(skuInfoEntity.getSkuId());
                    return skuSaleAttrValueEntity;
                }).collect(Collectors.toList());
                skuSaleAttrValueService.saveBatch(skuSaleAttrValueEntities);

                //设置sku的图片
                if (t.getImages() != null && t.getImages().size() > 0) {
                    List<SkuImagesEntity> skuImagesEntities = t.getImages().stream().map(images -> {

                        SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                        BeanUtils.copyProperties(images, skuImagesEntity);
                        skuImagesEntity.setSkuId(skuInfoEntity.getSkuId());
                        return skuImagesEntity;

                    }).filter(entity -> {
                        return !StringUtils.isEmpty(entity.getImgUrl());
                    }).collect(Collectors.toList());
                    skuImagesService.saveBatch(skuImagesEntities);
                }
                //保存商品满减信息,保存商品阶梯价格,会员价格等
                SkuReductionTO skuReductionTO = new SkuReductionTO();
                BeanUtils.copyProperties(t, skuReductionTO);
                skuReductionTO.setSkuId(skuInfoEntity.getSkuId());
                if (skuReductionTO.getFullCount() > 0 || skuReductionTO.getFullPrice().compareTo(BigDecimal.valueOf(0)) == 1) {
                    R r1 = couponFeignApi.saveSkuReduction(skuReductionTO);
                    if (r1.getCode() != 0) {
                        log.error("远程保存spu积分信息失败");
                    }
                }


            });
        }


    }

    @Override
    @Transactional
    public void up(Long spuId) {
        //设置规格属性
        List<ProductAttrValueEntity> list = productAttrValueService.lambdaQuery().eq(ProductAttrValueEntity::getSpuId, spuId).list();
        List<Long> attrIds = list.stream().map(ProductAttrValueEntity::getAttrId).collect(Collectors.toList());
        List<AttrEntity> entities = attrService.lambdaQuery().in(AttrEntity::getAttrId, attrIds).eq(AttrEntity::getSearchType, 1).list();
        List<SkuEsModel.Attrs> collect = entities.stream().map(item -> {
            SkuEsModel.Attrs attrs = new SkuEsModel.Attrs();
            attrs.setAttrId(item.getAttrId());
            attrs.setAttrName(item.getAttrName());
            ProductAttrValueEntity one = productAttrValueService.lambdaQuery().eq(ProductAttrValueEntity::getAttrId, item.getAttrId())
                    .eq(ProductAttrValueEntity::getSpuId, spuId).one();
            attrs.setAttrValue(one.getAttrValue());
            return attrs;
        }).collect(Collectors.toList());
        List<SkuInfoEntity> skuInfoEntities = skuInfoService.getBaseMapper().selectList(
                new QueryWrapper<SkuInfoEntity>().lambda().eq(SkuInfoEntity::getSpuId, spuId)
        );

        //远程调用设置库存
        List<Long> skuIds = skuInfoEntities.stream().map(SkuInfoEntity::getSkuId).collect(Collectors.toList());
        Map<Long, Boolean> hasStock = null;
        try {
            List<SkuHasStockVo> skuHasStockVos = wareFeignApi.hasStock(skuIds);
            hasStock = skuHasStockVos.stream().collect(Collectors.toMap(SkuHasStockVo::getSkuId, SkuHasStockVo::getHasStock));
        } catch (Exception e) {
            log.error("库存服务查询异常：原因{}", e);
        }

        Map<Long, Boolean> finalHasStock = hasStock;
        List<SkuEsModel> modelList = skuInfoEntities.stream().map(t -> {
            //组装数据
            SkuEsModel skuEsModel = new SkuEsModel();
            //设置spuId
            skuEsModel.setSpuId(spuId);
            skuEsModel.setSkuId(t.getSkuId());
            skuEsModel.setSkuTitle(t.getSkuTitle());
            skuEsModel.setSkuPrice(t.getPrice());
            skuEsModel.setSkuImg(t.getSkuDefaultImg());
            skuEsModel.setSelectCount(t.getSaleCount());
            //设置库存;
            if (finalHasStock != null) {
                skuEsModel.setHasStock(finalHasStock.get(t.getSkuId()));
            } else {
                skuEsModel.setHasStock(true);
            }
            //设置热度评分
            skuEsModel.setHotScore(0L);

            skuEsModel.setBrandId(t.getBrandId());
            skuEsModel.setCatelogId(t.getCatalogId());

            CategoryEntity category = categoryService.getById(t.getCatalogId());
            if (category != null) {
                skuEsModel.setCatelogName(category.getName());
            }
            BrandEntity byId = brandService.getById(t.getBrandId());
            if (byId != null) {
                skuEsModel.setBrandName(byId.getName());
                skuEsModel.setBrandImg(byId.getLogo());
            }
            //设置规格属性
            skuEsModel.setAttrs(collect);
            return skuEsModel;
        }).collect(Collectors.toList());

        //将数据远程发送给es进行保存

        System.out.println("搜索：" + modelList);


        R r = searchFeignApi.productSave(modelList);
        if (r.getCode() == 0) {
            //修改上架状态
            this.update(new UpdateWrapper<SpuInfoEntity>().lambda()
                    .set(SpuInfoEntity::getPublishStatus, SpuPublishStatus.PublishStatus.SPU_UP.getCode())
                    .eq(SpuInfoEntity::getId, spuId)
            );
        } else {
            //TODO 重复调用，接口的幂等性，重试机制
        }
    }

}